package com.lxlg.lxlg_order.common.redisconfig;

import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.HashMap;
@Component
public class ObjectRedisTemplate extends RedisTemplate<String, Object> {

    public ObjectRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
        setConnectionFactory(redisConnectionFactory);
        setKeySerializer(RedisSerializer.string());
        setValueSerializer(RedisSerializer.json());
        setHashKeySerializer(RedisSerializer.string());
        setHashValueSerializer(RedisSerializer.string());
        afterPropertiesSet();
    }

    public <T> T get(String key, Class<T> type) {
        return (T) opsForValue().get(key);
    }

    public void addHashObject(String key, Object obj) {
        Class<?> type = obj.getClass();
        Field[] fields = type.getDeclaredFields();

        HashMap<String, Object> map = new HashMap<>();

        for (Field field : fields) {
            field.setAccessible(true);
            try {
                Object value = field.get(obj);
                map.put(field.getName(), value.toString());
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        opsForHash().putAll(key, map);
    }


}
